<template>
  <div class="app-container">
    <el-form 
      ref="Form" 
      :model="Form" 
      :rules="rules"
      class="FormStyle"
      label-width="120px"
    >
      <div class="itemStyle">
        <el-form-item 
          label="套餐名称:" 
          prop="name"
          class="formStyle" 
        >
          <el-input 
            v-model="Form.name" 
            placeholder="请填写套餐名称"
            class="input1Style"
          />
        </el-form-item>
        <el-form-item 
          label="套餐分类:" 
          prop="idType"
        >
          <el-select
            v-model="Form.idType" 
            placeholder="请选择套餐分类"
            class="input1Style"
            @change="$forceUpdate()"
          >
            <el-option 
              v-for="(item, index) in setMealList" 
              :key="index" 
              :label="item.name" 
              :value="item.id" 
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item 
          label="套餐价格:" 
          prop="price"
          width="300"
          class="formStyle"
        >
          <el-input 
            v-model="Form.price"
            placeholder="请设置套餐价格"
            class="input1Style"
          />
        </el-form-item>
      </div>
      <el-form-item 
        label="口味做法配置:"
        class="tasteStyle"
      >
        <el-form-item>
          <div class="flavourBox">
            <span
              v-if="open == ''"
              class="addTaste"
              @click="addTaste"
            > + 添加菜品</span>
            <div v-if="open != 0" class="content">
              <el-card class="box-card">
                <div 
                  class="addTaste2" 
                  style="margin-bottom: 20px" 
                  @click="addTaste"
                >+ 添加菜品</div>
                <el-table
                  :data="tableData"
                  style="width: 100%"
                >
                <el-table-column
                  prop="name"
                  label="名称"
                />
                <el-table-column
                  prop="price"
                  label="原价"
                >
                  <template slot-scope="scope"> ￥{{ Number(scope.row.price) / 100 }} </template>
                </el-table-column>
                <el-table-column
                  prop="address"
                  label="份数"
                >
                <template slot-scope="scope">
                  <el-input-number 
                    v-model="scope.row.copies" 
                    @change="handleChange" 
                    :min="1" 
                    :max="10" 
                    label="描述文字" 
                  />
                </template>
                </el-table-column>
                <el-table-column
                  prop="click"
                  label="操作"
                  width="100"
                >
                  <template slot-scope="scope">
                    <el-button 
                      type="text" 
                      size="small"
                      @click.native.prevent="deleteRow(scope.$index, tableData)" 
                    >删除</el-button>
                  </template>
                </el-table-column>
                </el-table>
              </el-card>
            </div>
          </div>
        </el-form-item>
      </el-form-item>
      <el-form-item 
        label="套餐图片:" 
        prop="image"
      >
        <el-upload
          class="avatar-uploader"
          :action="`${env}/common/upload`"
          :on-success="handleAvatarSuccess"
          :show-file-list="false"
        >
          <img 
            v-if="imageUrl" 
            :src="imageUrl" 
            class="avatar" 
          />
          <i 
            v-else 
            class="el-icon-plus avatar-uploader-icon"
          ></i>
        </el-upload>
      </el-form-item>
      <div class="address">
        <el-form-item
          label="套餐描述:"
          prop="region"
        >
          <el-input
            v-model="Form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入套餐描述,最长不超过200字"
            maxlength="200"
            class="textareaStyle"
          />
        </el-form-item>
      </div> 
      <el-form-item class="buttonStyle">
        <el-button 
          @click="onCancel" 
          class="button1Style" 
        >Cancel</el-button>
        <el-button 
          @click="onSubmit" 
          class="button2Style"
        >Save</el-button>
      </el-form-item>
    </el-form>
    <el-dialog
      title="添加菜品"
      class="addDishList"
      :visible.sync="dialogHidden"
      width="60%"
    >
      <el-input
        v-model="value"
        class="searchDish"
        placeholder="请输入菜品名称进行搜索"
        style="width: 250px"
        @keyup.enter.native="ComboSearch"
        size="small"
        clearable
      >
        <i 
          slot="prefix" 
          class="el-input__icon el-icon-search" 
          style="cursor: pointer" 
          @click="ComboSearch"
        />
      </el-input>
      <div class="addDishCon">
        <div class="leftCont">
          <div
            v-show="seachKey.trim() == ''"
            class="tabBut"
          >
            <span
              v-for="(item, index1) in dishType"
              :key="index1"
              :class="{act:index == keyInd}"
              @click="checkTypeHandle(index1, item.id)"
            >{{item.name}}</span>
          </div>
          <div class="tabList">
            <div class="table">
              <div v-if="dishAddList.length === 0" style="padding-left:10px">
                暂无菜品!
              </div>
              <el-checkbox-group
                v-if="dishAddList.length > 0"
                v-model="selectedList"
                @change="selectedListHandle"
              >
                <div
                  v-for="(item, index2) in dishAddList"
                  :key="index2"
                  class="items"
                >
                  <el-checkbox
                    :key="index"
                    :label="item"
                  > 
                    <div class="item">
                      <span style="flex: 3;text-align: left">{{item.name}}</span>
                      <span>{{item.status===1?'在售':'已售'}}</span>
                      <span>￥{{item.price/100}}</span>
                    </div>
                  </el-checkbox> 
                </div>
              </el-checkbox-group>
            </div>
          </div>
        </div>
        <div class="ritCont">
          <div class="tit">
            已选菜品({{selectedList.length}})
          </div>
          <div 
            class="item2"
            v-for="(item,index3) in selectedList"
            :key="index3"
          >
            <div class="Item" style="display:flex">
              <span>{{item.name}}</span>
              <span>￥{{item.price/100}}</span>
              <span 
                class="delDishes"
                @click="delDishes(index)"
              >X</span>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button 
          @click="reMove"
        >Cancel</el-button>
        <el-button 
          type="primary" 
          @click="saveTableList"
        >save</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { querySetmealById, editSetmeal, addSetmeal } from '@/api/combo'
import { getCategoryList, getDishesList, queryDishesList } from '@/api/dishes'
export default ({
  data() {
    return {
      env: process.env.VUE_APP_BASE_API,
      imageUrl: "",
      id: '',
      textarea: '',
      dishTable: '',
      action: '',
      open: '',
      seachKey:'',
      value: '',
      submitType: '',
      dishList: [],
      index: 0,
      setmealDishes:'',
      inputVisible: false,
      inputValue: '',
      setMealList:[],
      Form: {
        name: '',
        categoryId:'',
        price: '',
        code:'',
        image: '',
        description: '',
        dishFlavours: [],
        status: 1,
        idType:''
      },
      tableData:[],
      keyInd:'',
      dishType: [],
      selectedList: [],
      dishAddList: [],
      dialogHidden: false,
      num: 1,
      rules: {
        name: [
          { required: true, message: "请输入套餐名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        price: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === "") {
                callback(new Error("价格必须填写"));
              }
              callback();
            },
            trigger: "blur",
          }
        ],
        idType: {
          required: true,
          message: '请选择套餐分类',
          trigger: 'change',
        },
      },
    }
  },
  watch: {
    seachKey(value) {
      if (value.trim()) {
        this.getDishForName(this.seachKey)
      }
    },
    selectedList(value){
      this.selectedList = value
    }
  },
  created() {
    const {
      query: { action, id },
    } = this.$route;
    this.action = action;
    this.id = id;
    if (this.action === 'EDIT' && id) {
      this.fechData()
    }
    this.getDishesList()
    this.getDishList()
    this.getDishTypeList()
  },
  methods: {
    async fechData() {
      querySetmealById(this.id).then(res => {
        console.log(res)
        this.Form = res.data
        this.Form.status = res.data.status === '1'
        this.imageUrl = this.env + `/common/download?name=${res.data.image}`
        this.Form.price = String(res.data.price / 100)
        this.Form.idType = res.data.categoryId
        this.selectedList = res.data.setmealDishes
        this.dishTable = res.data.setmealDishes
      })
    },
    ComboSearch() {
      this.seachKey = this.value
    },
    //获取图片
    handleAvatarSuccess(res) {
      this.Form.image = res.data;
      this.imageUrl = this.env + `/common/download?name=${res.data}`;
    },
    //添加口味
    addTaste() {
      this.dialogHidden = true;
      this.open = 1;
    },
    //获取菜品
    getDishesList() {
      getDishesList().then(res => {
        this.dishType = res.data
      }).catch(err => {
        this.$message.error('操作失败' + err)
      })
    },
    //获取套餐type
    getDishTypeList() {
      getCategoryList({ type: 2 }).then((res) => {
        console.log(res)
        this.setMealList = res.data.map((obj) => ({
          ...obj,
          idType: obj.id
        }))
      })
    },
    //
    getDishList(id) {
      queryDishesList({ categoryId: id }).then(res => {
        console.log(res)
        if (res.data.length == 0) {
          this.dishAddList = []
          return
        }
        let arr = res.data
        arr.map((n) => {
          n.dishId = n.id
          n.copies = 1
          n.dishName = n.name
        })
        this.dishAddList = arr
      })
    },
    // 获取添加菜品数据
    getSelectedList(value) {
      this.selectedList = [...value]
    },
    selectedListHandle(value) {
      this.getSelectedList(this.selectedList)
    },
    // 保存添加菜品列表
    saveTableList() {
      this.tableData = JSON.parse(JSON.stringify(this.selectedList))
      this.tableData.forEach((n) => {
        n.copies = 1
      })
      this.dialogHidden = false
      this.selectedList = []
    },
    onSubmit() {
      this.$refs.Form.validate(async (valid) => {
        let params = { ...this.Form }
        params.categoryId = this.Form.idType
        params.price *= 100
        params.setmealDishes = this.tableData.map((obj) => ({
          copies: obj.copies,
          dishId: obj.dishId,
          name: obj.name,
          price: obj.price,
        }))
        params.status = this.Form ? 1 : 0
        if (valid) {
          if (this.action === 'EDIT') {
            await editSetmeal(params)
            this.$message.success("编辑成功");
          } else {
            delete params.id
            await addSetmeal(params);
            this.$message.success("新增成功");
          }
          this.$router.push('/combo');
        }
      })
    },
    checkTypeHandle (ind,id) {
      this.keyInd = ind
      this.getDishList(id)
    },
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    //删除弹出框菜品
    delDishes(index) {
      this.selectedList.splice(index,1)
    },
    //取消添加新套餐
    onCancel() {
      this.$router.go(-1);
    },
    //关闭弹窗
    reMove() {
      this.dialogHidden = false
    }
  }
})
</script>
<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style lang="scss" scoped>
.app-container{
  width: 100%;
  height: 100%;
  background-color: #fff;
  .FormStyle{
    margin-left:80px;
    .itemStyle{
      margin-top:20px;
      .input1Style{
        width: 40% !important;
        font-size:16px;
      }
    }
    .tasteStyle{
      .addTaste{
        padding:15px 15px;
        text-align: center;
        border-radius:10px;
        cursor:pointer;
        font-size: 18px;
        background-color:pink;
        color:rgba(0,0,0,.5);
      }
      .addTaste:hover{
        color:white;
      }
      .content{
        .box-card{
          width: 70%;
          .addTaste2{
            width: 120px;
            padding:5px 5px;
            cursor:pointer;
            color:rgba(0,0,0,.5);
            background-color:pink;
            border-radius:10px;
            text-align: center;
          }
        }
      }
    }
    .address{
      margin: 20px 10px 20px 0px;
      height: 100px;
      width: 800px;
      .textareaStyle{
        height: 100%;
        width: 650px;
      }
    }
    .buttonStyle{
      margin-left:500px;
      margin-top:150px;
      .button1Style{
        width: 120px;
        height: 50px;
        font-size:20px;
        color:grey;
      }
      .button1Style:hover{
        border-color:rgb(249, 222, 227);
        color:white;
        background-color: rgb(249, 222, 227);
      }
      .button2Style{
        width:120px;
        height: 50px;
        font-size:20px;
        background-color: pink;
        color:grey;
        border:none;
      }
      .button2Style:hover{
        color:white;
      }
      .button3Style{
        height: 50px;
        font-size:20px;
        background-color: skyblue;
        color:grey;
        border:none;
      }
      .button3Style:hover{
        color:white;
      }
    }
  }
  .addDishList{
  width: 100%;
  height: 100%;
  .searchDish {
    position: absolute;
    top: 0px;
    right: 20px;
    .el-icon-search{
      font-size: 18px;
    }
  }
  .addDishCon {
    padding: 0 20px;
    display: flex;
    line-height: 40px;
    height: 70%;
    .leftCont {
      display: flex;
      border-right: solid 2px #E4E7ED;
      width: 60%;
      height: 20rem;
      padding: 15px;
      .tabBut {
        overflow-x: hidden;
        overflow-y: scroll;
        width: 150px;
        span {
          display: block;
          text-align: center;
          border-right: solid 2px #f4f4f4;
          cursor: pointer;
        }
      }
      .tabList {
        flex: 1;
        padding: 15px;
        overflow: hidden; 
        .table {
          border: solid 1px #f4f4f4;
          border-bottom: solid 1px #f4f4f4;
          .items {
            border-bottom: solid 1px #f4f4f4;
            padding: 0 10px;
            .item {
              display: flex;
              text-align: center;
              border-radius: 6px;
              color: #818693;
              span{
                display: inline-block;
                text-align: center;
                flex: 1;
              }
            }
          }
        }
      }
    }
    .ritCont {
      width: 40%;
      padding: 0 15px;
      .item2 {
        text-align: center;
        border-radius: 6px;
        border:1px solid rgba(0,0,0,.05);
        color: #818693;
        span{
          display: inline-block;
          text-align: center;
          flex: 1;
        }
        .delDishes{
          cursor: pointer;
        }
      }
      .item span:first-child {
        text-align: left;
        color: #20232A;
      }
    }
  }
  .dialog-footer{
    margin-top:50px;
  }
  }
}
</style>